
var calendar = function (year, month) {
    var date = null;
    if (arguments.length == 2) {
        date = this.parseISO8601(year + "-" + (month.toString().length == 1 ? ("0" + month) : month) + "-01");
    } else {
        date = new Date();
    }
    this.init(date);
};
calendar.prototype = {
    WeekShow: ["日", "一", "二", "三", "四", "五", "六"],
    container: "",
    init: function (date) {
        this.NowDate = date;
    },
    toString: function () {
        var month = this.NowDate.getMonth() + 1;
        var days = this.NowDate.getDate();
        if (month.length == 1) {
            month = "0" + month;
        }
        if (days.length == 1) {
            days = "0" + days;
        }
        return this.NowDate.getFullYear() + "年" + month.toString() + "月";
    },
    DayArray: new Array(),
    theadHtml: function () {
        var thead = $("<thead></thead>");
        var tr = $("<tr></tr>");
        thead.append(tr);
        for (i in this.WeekShow) {
            tr.append($("<th></th>").text(this.WeekShow[i]));
        }
        return thead;
    },
    renderMonth: function (callback) {
        if (typeof callback == "function") {
            this._renderMonth = callback;
        }

    },
    render: function (callback) {
        if (this.NowDate == "Invalid Date") {
            return;
        }
        var table = $("<table></table>").addClass("calendar");
        var tbody = $("<tbody></tbody>");
        table.append(this.theadHtml());
        var tr = $("<tr></tr>");
        this.DayArray.length = 0;

        var lastDay = this.MonthLastDay();
        this.NowDate.setDate(1);
        var year = this.NowDate.getFullYear();
        var month = this.NowDate.getMonth() + 1;
        if (month.toString().length == 1) {
            month = "0" + month;
        }
        var fristDayWeek = this.NowDate.getDay();
        if (fristDayWeek == 0) {
            fristDayWeek = 7;
        } else {
            for (i = 0; i < fristDayWeek; i++) {
                tr.append($("<td></td>").html("&nbsp;"));
            }
        }
        for (i = 1; i <= lastDay; i++) {
            var eachDate = this.parseISO8601(year + "-" + month + "-" + (i.toString().length == 1 ? ("0" + i) : i));
            var week = eachDate.getDay();
            if (week == 0) {
                week = 7;
            }
            if (week == 7) {//周日
                tr = $("<tr></tr>");
            }
            var td = $("<td></td>").attr("date", year + "-" + month + "-" + (i.toString().length == 1 ? ("0" + i) : i));
            this.DayArray.push(td);
            tr.append(td);
            if (week == 6) {//周六
                tbody.append(tr);
            }
        }
        var lastDayWeek = this.parseISO8601(year + "-" + month + "-" + (lastDay.toString().length == 1 ? ("0" + lastDay) : lastDay)).getDay();
        if (lastDayWeek != 6) {
            for (i = 0; i < 6 - lastDayWeek; i++) {
                tr.append($("<td></td>").html("&nbsp;"));
            }
            tbody.append(tr);
        }
        table.append(tbody);
        $(document.getElementById(this.container)).empty().append(table);
        if (this.renderEvent && typeof this.renderEvent == "function") {
            for (idx in this.DayArray)
                this.renderEvent.call(this.DayArray[idx], this.parseISO8601(this.DayArray[idx].attr("date")));
        } else if (typeof callback == "function") {
            if (!this.renderEvent) {
                this.renderEvent = callback;
            }
            for (idx in this.DayArray)
                callback.call(this.DayArray[idx], this.parseISO8601(this.DayArray[idx].attr("date")));
        }
        if (typeof this._renderMonth == "function") {
            this._renderMonth.call(this, this.toString());
        }

    },
    MonthLastDay: function () {
        var currentMonth = this.NowDate.getMonth();
        var nextMonth = ++currentMonth;
        var nextMonthFirstDay = new Date(this.NowDate.getFullYear(), nextMonth, 1);
        var oneDay = 1000 * 60 * 60 * 24;
        return new Date(nextMonthFirstDay - oneDay).getDate();
    },
    prevMonth: function (callback) {
        this.NowDate = this.DateAdd('m', -1, this.NowDate);
        this.render(callback);
    },
    nextMonth: function (callback) {
        this.NowDate = this.DateAdd('m', 1, this.NowDate);
        this.render(callback);
    },
    changeDate: function (year, month, callback) {
        this.NowDate = this.parseISO8601(year + "-" + month + "-01");
        this.render(callback);
    },
    select: function (date) {
        for (idx = 0, len = this.DayArray.length; idx < len; idx++) {
            if (date == this.DayArray[idx].attr("date")) {
                return this.DayArray[idx];
            }
        }
        return null;
    },
    parseISO8601: function (dateStringInRange) {
        var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
            date = new Date(NaN), month,
            parts = isoExp.exec(dateStringInRange);

        if (parts) {
            month = +parts[2];
            date.setFullYear(parts[1], month - 1, parts[3]);
            if (month != date.getMonth() + 1) {
                date.setTime(NaN);
            }
        }
        return date;
    },
    DateAdd: function (strInterval, NumDay, dtDate) {
        var dtTmp = new Date(dtDate);
        if (isNaN(dtTmp)) dtTmp = new Date();
        switch (strInterval) {
            case "s":
                dtTmp = new Date(Date.parse(dtTmp) + (1000 * parseInt(NumDay)));
                break;
            case "n":
                dtTmp = new Date(Date.parse(dtTmp) + (60000 * parseInt(NumDay)));
                break;
            case "h":
                dtTmp = new Date(Date.parse(dtTmp) + (3600000 * parseInt(NumDay)));
                break;
            case "d":
                dtTmp = new Date(Date.parse(dtTmp) + (86400000 * parseInt(NumDay)));
                break;
            case "w":
                dtTmp = new Date(Date.parse(dtTmp) + ((86400000 * 7) * parseInt(NumDay)));
                break;
            case "m":
                dtTmp = new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + parseInt(NumDay), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
                break;
            case "y":
                dtTmp = new Date(dtTmp.getFullYear() + parseInt(NumDay), dtTmp.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
                break;

        }
        return dtTmp;

    }

};



var cal = new calendar();
//cal.WeekShow = ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
cal.renderMonth(function (date) {
    $("#MonthShow").html(date);
});
cal.container = "calShow";


var jsonDate =rel;  //alert(jsonDate);
var dateNow = new Date();
dateNow = dateNow.getFullYear().toString() + dateNow.getMonth().toString() + dateNow.getDate().toString();
window.onload = function () {
    cal.render(function (day) {
        var $this = this;
        if (dateNow == (day.getFullYear().toString() + day.getMonth().toString() + day.getDate().toString())) {
            $this.addClass("today").html(day.getDate());
        } else
            $this.hover(function () {
                $(this).addClass("today1");
            }, function () {
                $(this).removeClass("today1");

            }).html(day.getDate());
    });

    //乘法函数，用来得到精确的乘法结果
//说明：javascript的乘法结果会有误差，在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
//调用：accMul(arg1,arg2)
//返回值：arg1乘以 arg2的精确结果
    function accMul(arg1)
    {
        var val=arg1.toFixed(2);
        return val;
    }

    var fn = function () {
        for (i in jsonDate) {
            var data = jsonDate[i];
            var query = cal.select(data.Date);
            if (query) {
                var html = new Array();

                // html.push("销售日期:" + data.Date + "<br />");
                // html.push("过期时间:" + data.ExpireDate + "<br />");
                html.push("<span class='day'>" + parseInt(query.attr("date").split('-')[2]) + " </span ><br />");
                // html.push("市场价:" + data.MarketPrice + "<br />");
                html.push("<span class='pric'>"  + data.SalePrice + " </span ><br />");//+ "&yen;"
                html.push("<span class='num'>" + data.Quantity + "张" + " </span ><br />");

                query.click(function () {
                    // alert("您选择了：" + $(this).attr("date"));

                    var dayprice=$(this).find('.pric').text();//选中当天的单价
                    var nums=$("#quantity").val();//购买数量
                    $("#SalePrice").val(dayprice);
                    /*$("#SalePrice").val(dayprice);*/
                    /*if($("#sale_price").val(dayprice)!=''){
                     $("#sale_price").val(dayprice);
                     }else{
                     $("#sale_price").val(dayprice)= $(this).find('.pric').text(); ;
                     }*/


                    $("#amountTotal").html(accMul(dayprice*nums));
                    //alert(nums);

                    $(".today").each(function(){
                        $(this).attr("class","");
                    });

                    $(this).attr("class","today");

                    $("#SaleDate").val($(this).attr("date"));

                    $(".month").hide();

                }).html(html.join(""));
            }
        }
    }

    fn();

    $("#prevMonth").click(function () {
        //$.ajax();
        cal.prevMonth();

        fn();
    });

    $("#nextMonth").click(function () {
        cal.nextMonth();

        fn();
    });

}

$(document).ready(function () {
    var ps = $("#SaleDate").position();
    $(".month").css("position", "absolute");
    $(".month").css("left", ps.left - 115); 	//距离左边距
    $(".month").css("top", ps.top - 0);			//距离上边距
    //$(".month").css("width", "111%");   		//日历表宽度
    $("#SaleDate").click(function () {
        $(".month").show();
    });
    $(".month").mouseleave(function () {
        $(".month").hide();
    });
});  